var Home = function () {
    this.$nav = $('.nav.nav-list');
    this.$tabs = $('#tabs');
    this.$menu = $('#menu');
};
Home.prototype = {
    init: function () {

        var self = this;
        // 获取广发通登录url
        $.get('/login/gft/url', function (res) {
            if (res.success) {
                $.Const.GFT_LOGIN_URL = res.data;
            }
        });
        // 初始化菜单
        this.$nav.ace_nav({
            url: '/member/module/menu/get',
            success: function () {
                // 浏览器刷新后加载当前hash
                self.loadPageByHash(self.$tabs);
            }
        });
        // 监控hash值得改变，进行添加tab
        $(window).off("hashchange").on("hashchange", function (event) {
            event.preventDefault();
            self.loadPageByHash(self.$tabs);
        });
        // 初始化tab
        this.$tabs
            .xumf_tab({
                homeLabel: '首页',
                activate: this.tabActivate
            })
            .xumf_tab('onMouseDown', function (event, eventType) {
                self.tabOnMouseDown(event, eventType, self.$menu)
            });

        // 1. 如何禁用默认鼠标右键菜单
        $('.page-content').contextmenu(function (event) {
            event.preventDefault();
            return false;
        });
        // 鼠标从menu区域内移开，隐藏menu
        this.$menu.mouseleave(function (e) {
            $(e.currentTarget).hide();
        });
        //初始化 菜单
        this.$menu.menu({
            position: {my: "left top", at: "right-5 top+5"},
            classes: {
                "ui-menu": "highlight"
            },
            select: function (event, ui) {
                self.menuSelect(event, ui, self.$menu, self.$tabs)
            }
        });

        // 绑定个性信息按钮
        $('#home_profile_action').on('click', function (event) {
            event.preventDefault();
            self.profileAction();
        });
        // 修改密码
        $("#password_change_action").on('click', function (event) {
            event.preventDefault();
            self.passwordAction();
        })
    },
    passwordAction: function () {
        var $form;
        layer.open({
            title: '修改密码',
            area: ['350px', '280px'],
            maxmin: false,
            content: '<div style="padding: 12px;">\
                        <form  class="form" action="/member/user/password/change/mine" method="POST">\
                            <div class="form-group">\
                                <label>原密码</label>\
                                <input type="password" autocomplete="off" name="oldPassword" class="form-control">\
                            </div>\
                            <div class="form-group">\
                                <label>新密码</label>\
                                <input type="password" autocomplete="off" name="newPassword" class="form-control">\
                            </div>\
                        </form>\
                      </div>',
            yes: function (index, layero) {
                if ($form.valid()) {
                    $form.submit();
                }
            },
            success: function (layero, index) {
                $form = $(layero).find('form');
                $form.validate({
                    rules: {
                        oldPassword: {
                            required: true,
                            minlength: 6,
                            maxlength: 100
                        },
                        newPassword: {
                            required: true,
                            minlength: 6,
                            maxlength: 100
                        }
                    },
                    errorElement: "em",
                    submitHandler: function (form) {
                        // 旧密码
                        var $oldPasswordInput = $form.find('input[name=oldPassword]');
                        var oldPassword = $oldPasswordInput.val();
                        // 新密码
                        var $newPasswordInput = $form.find('input[name=newPassword]');
                        var newPassword = $newPasswordInput.val();
                        // 加密后密码
                        var oldPasswordEncode = $.xumf.encrypt(oldPassword);
                        var newPasswordEncode = $.xumf.encrypt(newPassword);
                        // 设置值为密码的值为aes加密后
                        $oldPasswordInput.val(oldPasswordEncode);
                        $newPasswordInput.val(newPasswordEncode);
                        $(form).ajaxSubmit({
                            success: function (res) {
                                $.xumf.gritter(res);
                                layer.close(index);
                            }
                        });
                    }
                });
            }
        });
    },
    profileAction: function () {

        var formTemplate = _.template('<div style="padding: 12px;">\
                        <form  class="form" action="/member/user/mail/change" method="POST">\
                            <div class="form-group">\
                                <label>用户名</label>\
                                <input readonly autocomplete="off" value="{{username}}" class="form-control">\
                            </div>\
                            <div class="form-group">\
                                <label>登录名</label>\
                                <input readonly autocomplete="off" value="{{loginName}}" class="form-control">\
                            </div>\
                            <div class="form-group">\
                                <label>邮箱</label>\
                                <input {{emailReadonly}} type="email" autocomplete="off" name="email"  value="{{email}}" class="form-control">\
                                {{emailButton}}\
                            </div>\
                            <div class="form-group">\
                                <label>电话</label>\
                                <input readonly autocomplete="off" value="{{mobile}}" class="form-control">\
                            </div>\
                        </form>\
                      </div>');
        $.xumf.ajaxAndLoading({
            type: 'get',
            url: '/member/user/mine/info'
        }).done(function (res) {
            if (res.success) {
                var $form;
                var formVaule = $.extend({
                    mobile: '',
                    emailReadonly: res.data.employee ? '' : 'readonly',
                    emailButton: res.data.employee ? '<br><button type="submit" class="btn btn-success btn-sm">修改邮箱</button>' : ''
                }, res.data);
                layer.open({
                    title: '用户信息',
                    area: ['350px', '480px'],
                    maxmin: false,
                    content: formTemplate(formVaule),
                    btn: ["关闭"],
                    success: function (layero, index) {
                        $form = $(layero).find('form');
                        $form.validate({
                            rules: {
                                email: {
                                    required: true,
                                    email: true
                                }
                            },
                            errorElement: "em",
                            submitHandler: function (form) {
                                $(form).ajaxSubmit({
                                    success: function (res) {
                                        $.xumf.gritter(res);
                                        layer.close(index);
                                    }
                                });
                            }
                        });
                    }
                });
            } else {
                $.xumf.gritter(res);
            }
        });
    },
    /**
     * 菜单选择事件
     */
    menuSelect: function (event, ui, $menu, $tabs) {
        var index = $menu.find('li').index(event.currentTarget);
        switch (index) {
            case 0:
                $tabs.xumf_tab('removeTarget');
                break;
            case 1:
                $tabs.xumf_tab('removerTargetOutside');
                break;
            default:
                $tabs.xumf_tab('removeAll');
        }
        $menu.slideUp(100);
    },
    /**
     * tab 活动事件
     */
    tabActivate: function (event, ui) {
        // 切换menu菜单高亮样式
        var $nav = $('.nav.nav-list');
        var text = $(ui.newTab).children('a').text();
        $nav.find('li').removeClass('active');
        var $element = $nav.find('span:contains("' + text + '")').closest('li');
        $element.addClass('active');
    },
    tabOnMouseDown: function (event, eventType, $menu) {
        if ('right' === eventType) {
            // $menu.show();
            // 显示自定义菜单
            $menu.css({
                //定义菜单显示位置为事件发生的X坐标和Y坐标
                top: event.pageY - 50,
                left: event.pageX - 200
            }).slideDown(100);
        } else {
            //如果点击鼠标左键，隐藏菜单
            $menu.slideUp(100);
        }
    },
    /**
     * 加载当前的hash
     * @param $tabs tab控件
     */
    loadPageByHash: function ($tabs) {
        // 获取hash的url
        var url = $.trim(window.location.hash).replace('#', '');
        if ('' === url.trim()) return;
        // 为当前菜单添加活动状态
        var $element = $('.nav.nav-list').find('a[data-url="' + url + '"]').closest('li');
        if ($element.length > 0) {
            var label = $element.find('span').text();
            // 添加tab
            $tabs.xumf_tab('add', label, url, function (id, label, url) {
                if (url.indexOf('?') === -1) {
                    url += '?ajaxCertification=yes';
                } else {
                    url += '&ajaxCertification=yes';
                }
                $('#' + id).xumf_html_ajax({url: url});
            });
        }
    }
};

